package com.lagou.execute;

import com.lagou.config.BoundSql;
import com.lagou.config.Configuration;
import com.lagou.config.MapperStatement;
import com.lagou.util.GenericTokenParser;
import com.lagou.util.ParameterMapping;
import com.lagou.util.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by seemygo on 2020/11/13.
 */
public class SimpleExecute implements Execute {
    /**
     * 固定 jdbc和数据库的交互  贾琏预执事
     * @param configuration
     * @param mapperStatement
     * @param param
     * @return
     */
    public <E>List<E> query(Configuration configuration, MapperStatement mapperStatement, Object... param) throws Exception {
        //1,注册驱动加载连接
        Connection connection = configuration.getDataSource().getConnection();
        //2.0 对mapper.xml里面的sql进行解析  需要获取到jdbc可识别的sql语句形式
        String sql=mapperStatement.getSql();
        //此对象封装了最终jdbc需要的sql以及list集合（存放了占位符字段名称）
        BoundSql boundSql=getBoundSql(sql);
        String finalSql=boundSql.getSqlText();
        //获取参数类型
        Class<?> parameterType = mapperStatement.getParameterType();
        //2.1,获取预编译对象
        PreparedStatement preparedStatement = connection.prepareStatement(finalSql);
        //给每一个占位符设置参数
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            //给每一个sql #{}占位符赋值
            ParameterMapping parameterMap = parameterMappingList.get(i);
            String content = parameterMap.getContent();
            //反射
            Field declaredField = parameterType.getDeclaredField(content);
            declaredField.setAccessible(true);
            //System.out.println("param[0]的打印："+param[0]);
            Object o = declaredField.get(param[0]);
            //System.out.println(o);
            preparedStatement.setObject(i+1,o);
        }

        ResultSet resultSet = preparedStatement.executeQuery();
        Class<?> resultType = mapperStatement.getResultType();

        ArrayList<Object> objects=new ArrayList();
        while (resultSet.next()){
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object o = resultType.newInstance();
            int columnCount = metaData.getColumnCount();
            for (int i = 1; i < columnCount; i++) {
                //属性名
                String columnName = metaData.getColumnName(i);
                //属性值
                Object value = resultSet.getObject(columnName);
                //创建属性描述器 为属性生成读写方法
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultType);
                //获取写方法
                Method writeMethod = propertyDescriptor.getWriteMethod();
                //向类中写如值
                writeMethod.invoke(o,value);
            }
            objects.add(o);
        }


        return (List<E>) objects;
    }

    /**
     * Sql的封裝對象
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        //标记处理类：主要是配合通用标记解析器 GenericTokenParse完成了对文件的
        //解析工作  其中编辑处理器主要完成处理 TokenHandle
        ParameterMappingTokenHandler parameterMappingTokenHandler=new ParameterMappingTokenHandler();
        //GenericTokenParse 通用编辑解析器完成了对sql中占位符的解析
        //TokenHandle 编辑处理器后处理表达式
        //openToken  closeToken handle
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parseSql = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
        return boundSql;

    }


    /**
     * 插入修改删除的简单实现
     * @param configuration
     * @param mapperStatement
     * @param param
     */
    public void execute(Configuration configuration, MapperStatement mapperStatement, Object[] param) throws Exception {
        //1,注册驱动加载连接
        Connection connection = configuration.getDataSource().getConnection();
        //2.0 对mapper.xml里面的sql进行解析  需要获取到jdbc可识别的sql语句形式
        String sql=mapperStatement.getSql();
        //此对象封装了最终jdbc需要的sql以及list集合（存放了占位符字段名称）
        BoundSql boundSql=getBoundSql(sql);
        String finalSql=boundSql.getSqlText();
        //获取参数类型
        Class<?> parameterType = mapperStatement.getParameterType();
        //2.1,获取预编译对象
        PreparedStatement preparedStatement = connection.prepareStatement(finalSql);
        //给每一个占位符设置参数
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        //判断参数是否是基本数据类型
        if(parameterType.equals(java.lang.Integer.class)){
            preparedStatement.setObject(1,param[0]);
            System.out.println(param[0]);
        }else{
            for (int i = 0; i < parameterMappingList.size(); i++) {
                //给每一个sql #{}占位符赋值
                ParameterMapping parameterMap = parameterMappingList.get(i);
                String content = parameterMap.getContent();
                //反射
                Field declaredField = parameterType.getDeclaredField(content);
                declaredField.setAccessible(true);
                Object o = declaredField.get(param[0]);
                preparedStatement.setObject(i+1,o);
            }
        }
        System.out.println("最终sql打印"+finalSql);
        int resultSet = preparedStatement.executeUpdate();
    }




}
